<template>
  <div class="content">
    <!--    <van-sticky>-->
    <!--      <div class="head">-->
    <!--        <img @click="goBack" src="../assets/back.svg" alt="">-->
    <!--        <div>城市选择</div>-->
    <!--      </div>-->
    <!--      <div class="search" @click="handleSearch">-->
    <!--        <van-search v-model="searchCity" placeholder="输入城市名、拼音查询" />-->
    <!--      </div>-->
    <!--    </van-sticky>-->
    <van-sticky>
      <div class="head-wrap">
        <img @click="goBack" src="../assets/back.svg" alt="">
        <div class="search-wrap" @click="handleSearch">
          <van-search class="custom-search" v-model="searchCity" placeholder="输入城市名、拼音查询">
            <!-- <template #action>
                         <div>搜索</div>
                       </template> -->
          </van-search>

          <!-- <van-search :clearable="false" class="custom-search" v-model="searchCity" placeholder="输入城市名、拼音查询"
                            shape="round" :show-action="true" @search="handleSearch" background="transparent">
                            <template #action>
                                <div @click.stop="handleSearch" class="search-button">搜索</div>
                            </template>
                        </van-search> -->
        </div>
      </div>
    </van-sticky>
    <div style="padding: 0 10px 10px 0;box-sizing: border-box">
      <div class=" hot-city-copy">
        <div>当前所在地区</div>
        <div>
          <div>
            <van-icon name="location" color="#42a5f5" />
            <span>{{ cityName || $route.query.nowCity }}</span>
          </div>
        </div>
      </div>
      <div class="hot-city">
        <div>热门城市</div>
        <div>
          <div v-for="(x, y) in hotCity" @click="handleSel(x)">{{ x.city_name }}</div>
        </div>
      </div>
      <div class="card">
        <van-index-bar :index-list="indexList" ref="indexBar">
          <div v-for="(item, index) in cityData" :key="index">
            <van-index-anchor v-if="checkFirstOccurrence(item.first_letter, index) === index"
              :index="item.first_letter" />
            <van-cell @click="handleSel(item)" :title="item.city_name" />
          </div>
        </van-index-bar>
      </div>
    </div>
    <div>
      <van-overlay :lock-scroll="false" @touchmove.prevent :show="show" @click="show = false">
        <div class="wrapper">
          <div class="block">

            <div>
              <van-sticky>
                <van-search class="custom-search" ref="searchRef" @click.stop v-model="searchCity" show-action
                  placeholder="输入城市名、拼音或首字母查询" @input="onInput">
                  <template #action>
                    <div style="color: #000" @click="onCancel">取消</div>
                  </template>
                </van-search>
              </van-sticky>
            </div>
            <div v-if="searchCityList.length !== 0">
              <van-cell v-for="(item, index) in searchCityList" @click="handleSel(item)" :title="item.city_name"
                :key="index" />
            </div>
          </div>
        </div>
      </van-overlay>
    </div>

  </div>
</template>

<script>
import { pinyin } from 'pinyin';
import plantAPI from "@/api/plant";
import wx from "weixin-js-sdk";
import axios from "axios";
export default {
  beforeRouteLeave(to, from, next) {
    if (to.path === '/') {
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      requestAnimationFrame(() => {
        document.documentElement.scrollTop = 0;
      });
    }
    next();
  },
  data() {
    return {
      addressComponent: {},
      cityName: "",
      // 获取经纬度
      userLocation: {},
      cityDataLists: [],
      show: false,
      cityData: [],
      areaDateCopy: {},
      searchCity: '',
      searchCityList: [],
      indexList: [],
      hotCity: []
    };
  },
  created() {
    plantAPI.getcityAPI().then(res => {
      this.cityData = JSON.parse(res.data.body).data
      this.cityData.sort((a, b) => a.first_letter.localeCompare(b.first_letter));
      this.hotCity = []
      this.cityData.forEach(item => {
        if (item.is_hot === 1) {
          this.hotCity.push(item)
        }
      })

      this.cityData.forEach(item => {
        if (!this.indexList.includes(item.first_letter)) { // 检查是否已存在
          this.indexList.push(item.first_letter); // 不存在则添加
        }
      });

    })
    // this.cityData = this.processData(areaData)

  },
  mounted() {
    this.getLocationData();
    // setTimeout(() => {
    //   this.$refs.searchRef.focus()
    // }, 300)


  },
  methods: {
    async getCityData(longitude, latitude) {
      try {
        const amapApiKey = "839728157770fadb4fadb5bec227a298";
        const mapurl = `https://restapi.amap.com/v3/geocode/regeo?key=${amapApiKey}&location=${longitude},${latitude}&output=JSON&batch=false&roadlevel=0`;
        const response = await axios.get(mapurl);
        // 城市信息
        const { regeocode } = response.data;
        if (!regeocode) {
          return null;
        }
        const { addressComponent } = regeocode;
        this.addressComponent = addressComponent
        const city = addressComponent.city || addressComponent.district;
        this.cityName = city
        this.getCity_ID(this.cityName)
        localStorage.setItem("cityName", this.cityName)

      } catch (error) {
      }
    },
    getCity_ID(cityName) {
      this.cityData.forEach(element => {
        if (element.city_name == cityName || (element.city_name == (cityName.slice(0, -1)))) {
          localStorage.setItem("city_id", element.city_id)
        }
      });

    },
    getLocationByBrowser() {
      // 检查浏览器是否支持 Geolocation
      if (!navigator.geolocation) {
        this.$toast("浏览器不支持位置获取，请升级浏览器");
        return;
      }

      // 调用原生 API 获取位置
      navigator.geolocation.getCurrentPosition(
        (position) => {
          // 成功回调：获取经纬度
          const latitude = position.coords.latitude; // 纬度
          const longitude = position.coords.longitude; // 经度
          this.userLocation = {
            longitude, latitude
          }
          localStorage.setItem('longitude', this.userLocation.longitude)
          localStorage.setItem('latitude', this.userLocation.latitude)
          this.getCityData(this.userLocation.longitude, this.userLocation.latitude)
        },
        (error) => {
          let longitude = localStorage.getItem('longitude')
          let latitude = localStorage.getItem('latitude')
          this.getCityData(longitude, latitude)
        },
        {
          enableHighAccuracy: false, // 是否高精度定位（默认 false，true 可能更耗电）
          timeout: 1000000, // 超时时间（5秒）
          maximumAge: 0 // 是否允许使用缓存位置（0 表示不缓存）
        }
      );
    },
    getLocationByWechat() {
      const url = window.location.href.split('#')[0];
      plantAPI.wxSign({
        url
      }).then(res => {
        this.getWxConfigConfig({
          timestamp: res.data.timestamp,
          nonceStr: res.data.nonceStr,
          signature: res.data.signature,
        })
      })

    },
    async getWxConfigConfig(config) {
      try {
        wx.config({
          debug: false, // 开启调试模式（生产环境关闭），会在控制台输出 config 结果
          appId: "wxf6b22350d8075054", // 从后端获取，不要硬编码
          timestamp: config.timestamp.toString(), // 确保是字符串类型
          nonceStr: config.nonceStr,
          signature: config.signature,
          jsApiList: ["getLocation"]
        });

        // 监听 config 成功回调
        wx.ready(() => {
          wx.getLocation({
            type: "wgs84",
            timeout: 500000, // 超时时间建议设置 10000-15000ms（默认 10000ms）
            highAccuracyExpireTime: 500000, // 高精度定位超时时间（可选，仅支持高精度定位时生效）
            success: (res) => {
              const { longitude, latitude } = res;
              this.userLocation = { longitude, latitude };
              localStorage.setItem('longitude', this.userLocation.longitude)
              localStorage.setItem('latitude', this.userLocation.latitude)
              this.getCityData(this.userLocation.longitude, this.userLocation.latitude)
            },
            cancel: () => {
            },
            fail: (err) => {
              let name = localStorage.getItem("cityName")
              if (name) {
                this.cityName = name
              } else {
                this.cityName = '西安市'
              }
            }
          });
        });

        // 监听 config 失败回调
        wx.error((err) => {
          this.getLocationByBrowser()
          // 根据错误信息针对性解决（如签名错误、域名未配置等）
        });
      } catch (error) {
        let name = localStorage.getItem("cityName")
        if (name) {
          this.cityName = name
        } else {
          this.cityName = '西安市'
        }
      }
    },
    // 判断是否为微信内置浏览器
    isWechatBrowser() {
      const ua = window.navigator.userAgent.toLowerCase();
      return ua.includes('micromessenger'); // 微信浏览器的 userAgent 包含 "micromessenger"
    },
    getLocationData() {
      if (this.isWechatBrowser()) {
        this.getLocationByWechat();
      } else {
        this.getLocationByBrowser();
      }
    },
    onInput(val) {
      this.searchCityList = this.fuzzySearch(this.cityData, val);
      if (!val) {
        this.searchCityList = []
      }
    },
    onCancel() {
      this.show = false;
    },
    handleSearch() {
      this.$refs.searchRef.focus()
      this.show = true;

    },
    handleSel(e) {
      localStorage.setItem("cityName", e.city_name)
      localStorage.setItem("city_id", e.city_id)
      this.getCityCoords(e.city_name).then(coords => {
        localStorage.setItem('longitude', coords.lng)
        localStorage.setItem('latitude', coords.lat)
      });
      // 返回首页并传递城市参数
      // this.$router.replace({
      //   path: '/',
      //   query: {
      //     nowCity: e.city_name
      //   }
      // });

      this.$router.back()
    },
    goBack() {
      this.$router.go(-1)
      // this.$router.back()
    },
    async getCityCoords(cityName, adcode) {
      const key = '839728157770fadb4fadb5bec227a298';
      const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(cityName)}&city=${adcode}&key=${key}`;

      try {
        const response = await fetch(url);
        const data = await response.json();

        if (data.status === '1' && data.geocodes.length > 0) {
          const location = data.geocodes[0].location.split(',');
          return {
            lng: parseFloat(location[0]), // 经度
            lat: parseFloat(location[1])  // 纬度
          };
        }
        return null;
      } catch (error) {
        return null;
      }
    },
    checkFirstOccurrence(value, currentIndex) {
      // return array.findIndex(item => item === value) === currentIndex;
      return this.cityData.findIndex(item => item.first_letter === value);
    },
    fuzzySearch(array, keyword) {
      // const pinyin = require('pinyin')
      const lowerKeyword = keyword.toLowerCase();
      return array.filter(item => {
        // 生成全拼和首字母
        const fullPinyin = pinyin(item.city_name, { style: pinyin.STYLE_NORMAL })
          .flat()
          .join(" ")
          .toLowerCase();

        const initials = pinyin(item.city_name, { style: pinyin.STYLE_FIRST_LETTER })
          .flat()
          .join("")
          .toLowerCase();

        // 检查 name、全拼、首字母 是否包含关键词
        return (
          item.city_name.toLowerCase().includes(lowerKeyword) ||
          fullPinyin.includes(lowerKeyword) ||
          initials.includes(lowerKeyword)
        );
      });
    }

  },
};
</script>

<style scoped lang="scss">
.content {
  width: 100%;
  height: 100%;
  overflow: hidden;

  //padding: 0 10px;
  //box-sizing: border-box;
  ::v-deep .van-sticky {
    //background: #ffffff;
    //padding-left: 10px;
  }

  ::v-deep .van-index-anchor--sticky {
    top: 60px;
  }

  //.head {
  //  width: 100%;
  //  padding: 0 10px;
  //  box-sizing: border-box;
  //  height: 50px;
  //  display: flex;
  //  align-items: center;
  //
  //  img {
  //    width: 20px;
  //    height: 20px;
  //  }
  //
  //  >div {
  //    width: calc(100% - 20px);
  //    text-align: center;
  //    font-size: 16px;
  //    font-weight: bold;
  //  }
  //}

  //.search {
  //  width: 100%;
  //  padding: 0 10px 10px 10px;
  //  height: 50px;
  //  box-sizing: border-box;
  //
  //  .van-search {
  //    padding: 0;
  //  }
  //}

  .head-wrap {
    width: 100%;
    //height: 60px;
    //display: flex;
    //align-items: center;
    //background-color: #FFFFFF;
    //width: 375px;
    height: 64px;
    display: flex;
    align-items: center;
    background: linear-gradient(94deg,
        rgba(238, 71, 59, 0.05) 0%,
        rgba(246, 118, 109, 0.3) 58%,
        rgba(238, 71, 59, 0.3) 100%);
    color: #000;
    /* 文字颜色会保持不透明 */
    padding-left: 10px;

    img {
      width: 20px;
      height: 20px;
    }

    .search-wrap {
      width: calc(100% - 30px);
      padding: 0 10px;
      box-sizing: border-box;

      //background-color: #FFFFFF;
      .van-search {
        padding: 0;
        border-radius: 15px;
      }

      ::v-deep .van-search__content {
        background-color: #f3efef;
        border-radius: 15px;
      }

      ::v-deep .van-field__control::placeholder {
        color: #666666;
      }

    }
  }

  .hot-city {
    width: calc(100% - 20px);
    padding-left: 16px;
    box-sizing: border-box;

    >div:nth-child(1) {
      width: 100%;
      color: #666666;
      font-size: 14px;
    }

    >div:nth-child(2) {
      width: 100%;
      margin-top: 5px;
      display: flex;
      flex-wrap: wrap;
      flex: 4;
      justify-content: space-between;

      >div {
        flex: 0 0 calc(25% - 10px);
        width: 20%;
        text-align: center;
        box-sizing: border-box;
        padding: 5px 10px;
        border-radius: 5px;
        color: #000000;
        font-size: 14px;
        border: 1px solid #999999;
        margin-bottom: 10px;
      }
    }
  }

  .hot-city-copy {
    width: calc(100% - 20px);
    padding-left: 16px;
    box-sizing: border-box;

    >div:nth-child(1) {
      width: 100%;
      color: #666666;
      font-size: 14px;
    }

    >div:nth-child(2) {
      width: 100%;
      margin-top: 5px;
      display: flex;

      >div {
        text-align: center;
        box-sizing: border-box;
        padding: 5px 10px;
        border-radius: 5px;
        color: #000000;
        font-size: 14px;
        border: 1px solid #999999;
        margin-bottom: 10px;
      }
    }
  }


  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 100%;
    height: 100%;

    >div:nth-child(1) {
      padding: 10px 0;
      background: #FFFFFF;
    }

    >div:nth-child(2) {
      padding: 0 15px 10px 15px;
      box-sizing: border-box;
      background: #FFFFFF;
    }
  }
}

.van-overlay {
  z-index: 10;
  overflow: hidden;
}

.van-search__action {
  color: #42a5f5;
}

.van-search__content {
  background-color: #f3efef;
}

.van-field__control {
  color: #4c4b4b;
}

.search-button {
  color: #EE473B;
  padding: 0 8px;
  font-size: 14px;
  white-space: nowrap;
}
</style>
